const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    devs: [],
    setdeviceIdOff:''
  },
  /**
   * 自定义数据
   */
  customData: {
    _devs: []
  },
  /**
   * 监听页面加载
   */
  onLoad: function () {
    /**
     * 检查版本
     */
    if (app.getPlatform() == 'android' && this.versionCompare('6.5.7', app.getVersion())) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，请更新至最新版本',
        showCancel: false
      })
    }
    else if (app.getPlatform() == 'ios' && this.versionCompare('6.5.6', app.getVersion())) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，请更新至最新版本',
        showCancel: false
      })
    }
    /**
     * 微信蓝牙模块初始化
     */
    const self = this
    wx.openBluetoothAdapter({
      success: function (res) {
        // console.log('search.js[onLoad]: openBluetoothAdapter success')
        app.globalData.BluetoothState = true
        self.startSearchDevs() // 搜索附近蓝牙
      },
      fail: function (err) {
        // console.log('search.js[onLoad]: openBluetoothAdapter fail')
        if (err.errCode === 10001) { // 手机蓝牙未开启
          app.globalData.BluetoothState = false
          wx.showLoading({
            title: '请开启手机蓝牙',
          })
        } else {
          console.log(err.errMsg)
        }
      }
    })
    /**
     * 监听蓝牙适配器状态变化
     */
    wx.onBluetoothAdapterStateChange(function(res) {
      // console.log('search.js[onLoad]: onBluetoothAdapterStateChange')
      if (res.available) {
        // console.log('search.js[onLoad]: BluetoothState is true')
        app.globalData.BluetoothState = true
        wx.openBluetoothAdapter({
          success: function(res) {
            app.globalData.BluetoothState = true
            //wx.hideLoading()
          },
        })
      } else {
        // console.log('search.js[onLoad]: BluetoothState is false')
        app.globalData.BluetoothState = false
        app.globalData.connectState = false
        wx.showLoading({
          title: '请开启手机蓝牙',
        })
      }
    })
    /**
     * 监听BLE蓝牙连接状态变化
     */
    wx.onBLEConnectionStateChange(function(res) {
      if (res.connected) {
        // console.log('connected')
        //wx.hideLoading()
        wx.showLoading({
          title: '连接成功',
          icon: 'success',
          success: function(res) {
            app.globalData.connectState = true
          }
        })
      } else {
        // console.log('disconnect')
        //wx.hideLoading()
        wx.showLoading({
          title: '已断开连接',
          icon: 'none',
          success: function(res) {
            app.globalData.connectState = false
          }
        })
      }
      setTimeout(function () {
        wx.hideLoading()
      }, 1000)
    })
  },
  onShow: function () {
  },
  /**
   * 监听页面初次渲染完成
   */
  onReady: function () {
  },
  /**
   * 监听页面隐藏
   */
  onHide: function () {
    app.stopSearchDevs()
  },
  /**
   * 监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (app.globalData.BluetoothState) {
      const self = this
      this.customData._devs = []
      wx.closeBluetoothAdapter({
        success: function (res) {
          wx.openBluetoothAdapter({
            success: function (res) {
              self.startSearchDevs()
            }
          })
        }
      })
    }
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 2000)
  },
  /**
   * 开始搜索附近蓝牙
   */
  startSearchDevs: function () {
    const self = this
    wx.startBluetoothDevicesDiscovery({ // 开启搜索
      allowDuplicatesKey: false,
      success: function (res) {
        wx.onBluetoothDeviceFound(function (devices) {
          var isExist = false
          if (devices.deviceId) {
            for (let item of self.customData._devs) {
              if (item.deviceId === devices.deviceId) {
                isExist = true
                break;
              }
            }
            !isExist && self.customData._devs.push(devices)
            self.setData({
              devs: self.customData._devs
            })
          }
          else if (devices.devices) {
            for (let item of self.customData._devs) {
              if (item.deviceId === devices.devices[0].deviceId) {
                isExist = true
                break;
              }
            }
            !isExist && self.customData._devs.push(devices.devices[0])
            self.setData({
              devs: self.customData._devs
            })
          }
          else if (devices[0]) {
            for (let item of self.customData._devs) {
              if (item.deviceId === devices[0].deviceId) {
                isExist = true
                break;
              }
            }
            !isExist && self.customData._devs.push(devices[0])
            self.setData({
              devs: self.customData._devs
            })
          }
        })
      }
    })
  },

  /**
   * 停止搜索搜索附近蓝牙
   */
  stopSearchDevs: function () {
    app.stopSearchDevs()
  },
  /**
   * 关闭蓝牙
   */
  offBlueTooth: function () {
    if(app.globalData.BluetoothState){
      app.endConnect(this.setdeviceIdOff)
    }else{
      wx.showLoading({
        title: '请先连接蓝牙',
      })
    }
    setTimeout(function () {
        wx.hideLoading()
      }, 1000)
  },
  /**
   * 版本比较
   */
  versionCompare: function (ver1, ver2) {
    var version1pre = parseFloat(ver1)
    var version2pre = parseFloat(ver2)
    var version1next = parseInt(ver1.replace(version1pre + ".", ""))
    var version2next = parseInt(ver2.replace(version2pre + ".", ""))
    if (version1pre > version2pre)
      return true
    else if (version1pre < version2pre)
      return false
    else {
      if (version1next > version2next)
        return true
      else
        return false
    }
  },
  /**
   * 选择设备连接
   */
  connect (event) {
    console.log(app.globalData.BluetoothState)
    if (app.globalData.BluetoothState) {
      const deviceId = event.currentTarget.dataset.dev.deviceId
      const deviceName = event.currentTarget.dataset.dev.name
      this.setdeviceIdOff = deviceId
      wx.showLoading({
        title: '正在连接...',
      })
      //this.dispose02()
      //app.startConnect(deviceId, deviceName)
      this.startConnection(deviceId, deviceName)
    }
  },

  /*
*连接实现
*/ 
startConnection(deviceId, deviceName = '未知设备') {
  self = this
  if (app.globalData.BluetoothState) {
    wx.createBLEConnection({
      deviceId: deviceId,
      timeout: 10000, // 10s连接超时
      success: function (res) {
        console.log("连接成功..")
        self.nextView(deviceId,deviceName)
      },
    })
  }
},


    /*
  *处理02模块
  */ 
 dispose02(deviceId,deviceName,services){
  console.log("进入02处理函数..")
  for(var i =0; i<services.length;i++){
    if(services[i].uuid == "49535343-FE7D-4AE5-8FA9-9FAFD205E455" ){
      const serviceId = services[i].uuid
      const characteristicId = '49535343-1E4D-4BD9-BA61-23C647249616'
      wx.notifyBLECharacteristicValueChange({
        deviceId,
        serviceId,
        characteristicId,
        state: true,
        success: function(res) {
          console.log("通知打开成功..")
          wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: function(res) {
              console.log("获取特征值成功..")
              for(var i = 0; i<res.characteristics.length;i++){
                console.log("特征:  "+res.characteristics[i].uuid)
                if(res.characteristics[i].uuid == '49535343-8841-43F4-A8D4-ECBE34729BB3' ){
                  const characteristicId =  res.characteristics[i].uuid
                  const properties = []
                  properties.push("read="+res.characteristics[i].properties.read)
                  properties.push("write="+res.characteristics[i].properties.write)
                  properties.push("notify="+res.characteristics[i].properties.notify)
                  properties.push("indicate="+res.characteristics[i].properties.indicate)
                  console.log("res.characteristics[i].properties.write is   "+res.characteristics[i].properties.write)
                  wx.navigateTo({
                    url: `com/com?deviceId=${deviceId}&serviceId=${serviceId}&characteristicId=${characteristicId}&${properties.join('&')}`,
                  })
                  return true
                }
              }
  
            }
          })
        }
      })
      
    }
  }
  return false;
  },
    /*
  *下一个界面
  */ 
 nextView(deviceId,deviceName){
  console.log("进入nextView函数..")
  console.log("deviceId is "+deviceId)
  self = this
  wx.getBLEDeviceServices({
    deviceId,
    success: function(res) {
      console.log("获取服务成功..")
      const services = res.services.filter((item, i) => {
        return !/^000018/.test(item.uuid)
      })
      for(var i =0; i<services.length;i++){
        if(services[i].uuid == "0000FFE0-0000-1000-8000-00805F9B34FB" || services[i].uuid == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){//  || services[i].uuid == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
          const serviceId = services[i].uuid
          wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: function(res) {
              console.log("获取特征值成功..")
              for(var i = 0; i<res.characteristics.length;i++){
                console.log("特征:  "+res.characteristics[i].uuid)
                if(res.characteristics[i].uuid == '0000FFE1-0000-1000-8000-00805F9B34FB' || res.characteristics[i].uuid == '49535343-8841-43F4-A8D4-ECBE34729BB3'){// || res.characteristics[i].uuid == '49535343-8841-43F4-A8D4-ECBE34729BB3'
                  const characteristicId =  res.characteristics[i].uuid
                  const properties = []
                  properties.push("read="+res.characteristics[i].properties.read)
                  properties.push("write="+res.characteristics[i].properties.write)
                  properties.push("notify="+res.characteristics[i].properties.notify)
                  properties.push("indicate="+res.characteristics[i].properties.indicate)
                  console.log("res.characteristics[i].properties.write is   "+res.characteristics[i].properties.write)
                  wx.navigateTo({
                    url: `mgturret/mgturret?deviceId=${deviceId}&serviceId=${serviceId}&characteristicId=${characteristicId}&${properties.join('&')}`,
                  })
                }
              }

            }
          })
          return
        }
      }

      //wx.navigateTo({
        //url: `pages/service/service?deviceId=${deviceId}&deviceName=${deviceName}`,
      //})

    },
    fail: function(res) {
      wx.showToast({
        title: '设备服务获取失败',
        icon: 'none'
      })
    }
  })
  console.log("nextView函数执行完毕")
}
})